const express = require('express')
const app = express()
app.listen(3005, () => {
    console.log('http://login:3005 已开启');
})
const path = require('path')
const fs = require('fs')


app.get('/login', (req, res) => {
    const filepath = path.join(__dirname, 'login.html')
    res.sendFile(filepath)
})
app.get('/register', (req, res) => {
    const filepath = path.join(__dirname, 'register.html')
    res.sendFile(filepath)
})
app.get('', (req, res) => {
    res.send('<img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ff30740b90a656245940369bf5770ecc83c6285b215b43-ZQL6Vu_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636900866&t=0bd5fff1c07212356ccf34b4090581e0" style="display: block;width: 100%;height: 100%;">')
})

app.get('/dologin', (req, res) => {
    let sj = fs.readFileSync('./person.json', 'utf8') //字符串形式
    let w = JSON.parse(sj) //转对象

    let tf = w.findIndex(item => item.username == req.query.username && item.password == req.query.password)
    if (tf == -1) {
        res.send('<h1>登陆失败</h1>')
    } else {
        res.send('<h1>登录成功</h1>')
    }
})
app.get('/doregister', (req, res) => {
    let sj = fs.readFileSync('./person.json', 'utf8') //字符串形式
    let w = JSON.parse(sj) //转对象

    let tf = w.findIndex(item => item.username == req.query.username && item.password == req.query.password)
    if (tf == -1) {
        w.push(req.query)  //对象尾部添加
        w = JSON.stringify(w)  //对象转字符串
        fs.writeFileSync('./person.json', w, { flag: 'w' })
        // res.send('<h1>注册成功</h1>')
        const filepath = path.join(__dirname, 'login.html')
        res.sendFile(filepath)
    } else {
        res.send('<h1>注册失败</h1>')
    }
})